package inutan.robot.broker;

import bright.serialization.AbstractBean;
import bright.serialization.ByteBuf;
import org.ricks.common.exception.ServerBootstrapException;
import org.ricks.net.codec.DataCodec;

/**
 * @author chenwei
 * @Description:luban 协议解析处理
 * @date 2023/2/1511:19
 */
public class GameCodec implements DataCodec {
    @Override
    public byte[] encode(Object data) {
        if(data instanceof AbstractBean abstractBean) {
            ByteBuf byteBuf = ByteBuf.alloc();
            abstractBean.serialize(byteBuf);
            return byteBuf.array();
        }
        throw new ServerBootstrapException("序列化异常，不是Luban协议");
    }

    @Override
    public <T> T decode(byte[] data, Class<?> dataClass) {
        try {
            AbstractBean abstractBean = (AbstractBean) dataClass.getConstructor().newInstance();
            ByteBuf byteBuf = ByteBuf.alloc();
            byteBuf.replace(data);
            abstractBean.deserialize(byteBuf);
            return (T) abstractBean;
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new ServerBootstrapException("反序列化异常，不是Luban协议");
    }
}